package cn.lzy.Security.CSRF;

import cn.lzy.Security.redis.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: WeiKaiYe
 * @CreateTime: 2023-10-17  10:56
 */

@Controller
public class CsrfController {

    @Autowired
    private CustomerRepository customerRepository;

    // 向用户修改页跳转
    @GetMapping("/toUpdate")   // http://localhost:8080/toUpdate
    public String toUpdate(){
        return "csrf/csrfTest";
    }   // 实现浏览器修改页面

    // 用户修改提交处理
    @ResponseBody
    @PostMapping(value = "/updateUser")
    public String updateUser (@RequestParam String username, @RequestParam String password, HttpServletRequest request){
        System.out.println(username);
        System.out.println(password);
        String csrf_token = request.getParameter("_csrf");
        System.out.println(csrf_token);

        // 获取应用上下文
        SecurityContext context = SecurityContextHolder.getContext();
        // 获取登录的用户信息
        Authentication authentication = context.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        // 获取登录的用户id
        Integer updateId = customerRepository.findIdByUsername(principal.getUsername());
        // 更新用户表中对应id的用户名
        Integer result = customerRepository.updateById(username, updateId);

        return "ok，更新成功！";
    }
}
